package com.scau.classOnline.controller;

import com.scau.classOnline.entity.User;
import com.scau.classOnline.model.RespEntity;
import com.scau.classOnline.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/*
 *@Author: Mu
 *@Description:登录、注册、忘记密码
 *@Date:0:55 2019/7/12
 */
@RestController
@RequestMapping(value = "/")
public class SysController {
    @Autowired
    private UserService userService;

    /*
     *@Author: Mu
     *@Description:登录 直接调用"/login"即可，方法由框架实现，故此无代码
     *@Date:0:58 2019/7/12
     *params：post传入参数非json格式 例："http://127.0.0.1:8081/login?username=jack&password=654321"
     *returns:
     */
//    public RespEntity login(){}

    /*
     *@Author: Mu
     *@Description:注册
     *@Date:0:56 2019/7/12
     *params：前端传入json格式例：{"username":"jack","password":"123456","email":"qerqwr","status":1}
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public RespEntity register(@RequestBody(required = true) User user) {
        int i = userService.register(user);
        if (i == 1) {
            if (userService.addRolesForUser(user.getUsername()) == 1) {
                return RespEntity.ok("注册成功");
            } else {
                return RespEntity.error("注册失败");
            }
        } else if (i == -1) {
            return RespEntity.error("用户名重复，注册失败");
        }
        return RespEntity.error("注册失败!");
    }

    /*
     *@Author: Mu
     *@Description:忘记密码
     *@Date:0:57 2019/7/12
     *params：前端传入json格式例：{"username":"jack","email":"qerqwr","newPassword":"654321"}
     *returns:
     */
    @RequestMapping(value = "/forgetPwd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public RespEntity forgetPwd(@RequestBody Map<String, Object> map) {
        String username = (String) map.get("username");
        String email = ((String) map.get("email"));
        String newPassword = ((String) map.get("newPassword"));
        User user = userService.findByUsername(username);
        if (user == null){
            return RespEntity.error("该用户名不存在");
        }
        if (!user.getEmail().equals(email.trim())) {
            return RespEntity.error("该邮箱未绑定账号");
        }
        if (userService.motifyPassword(user.getId(), newPassword)) {
            return RespEntity.ok("修改成功");
        } else {
            return RespEntity.error("修改失败");
        }
    }
}
